package ui;

import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

public class RulePanel extends JPanel {
    private JComboBox<String> ruleTypeComboBox;
    private JTable ruleTable;
    private DefaultTableModel tableModel;
    private final List<Rule> rules;
    private JTextArea ruleContentArea;
    private JComboBox<String> logicComboBox;

    public RulePanel() {
        rules = new ArrayList<>();
        initializeComponents();
    }

    private void initializeComponents() {
        setLayout(new BorderLayout());

        // 创建输入面板
        JPanel inputPanel = new JPanel(new GridBagLayout());
        inputPanel.setBorder(BorderFactory.createTitledBorder("规则配置"));
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.anchor = GridBagConstraints.WEST; // 靠左对齐

        // 规则类型
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.weightx = 0.0; // 不允许组件在水平方向上扩展
        gbc.fill = GridBagConstraints.NONE; // 组件在单元格内不填充
        inputPanel.add(new JLabel("规则类型:"), gbc);

        gbc.gridx = 1;
        gbc.weightx = 0.0; // 不允许组件在水平方向上扩展
        gbc.fill = GridBagConstraints.NONE; // 组件在单元格内不填充
        ruleTypeComboBox = new JComboBox<>(new String[]{
                "状态码等于（数字）",
                "状态码不等于（数字）",
                "响应头包含（字符串）",
                "响应头不包含（字符串）",
                "响应头包含（正则）",
                "响应头不包含（正则）",
                "响应体包含（字符串）",
                "响应体不包含（字符串）",
                "响应体包含（正则）",
                "响应体不包含（正则）"
        });
        ruleTypeComboBox.setPreferredSize(new Dimension(300, ruleTypeComboBox.getPreferredSize().height));
        inputPanel.add(ruleTypeComboBox, gbc);

        // 规则内容
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.weightx = 0.0; // 不允许组件在水平方向上扩展
        gbc.fill = GridBagConstraints.NONE; // 组件在单元格内不填充
        gbc.anchor = GridBagConstraints.NORTHWEST; // 靠左上对齐
        inputPanel.add(new JLabel("规则内容："), gbc);

        gbc.gridx = 1;
        gbc.weightx = 1.0; // 允许组件在水平方向上扩展
        gbc.fill = GridBagConstraints.BOTH; // 组件在单元格内填充
        gbc.gridheight = 1;
        ruleContentArea = new JTextArea(3, 20);
        ruleContentArea.setLineWrap(true);
        ruleContentArea.setWrapStyleWord(true);
        JScrollPane contentScrollPane = new JScrollPane(ruleContentArea);
        contentScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        inputPanel.add(contentScrollPane, gbc);

        // 添加规则按钮
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.gridwidth = 2;
        gbc.weightx = 0.0; // 不允许组件在水平方向上扩展
        gbc.fill = GridBagConstraints.NONE; // 组件在单元格内不填充
        gbc.anchor = GridBagConstraints.CENTER; // 居中对齐
        JButton addButton = new JButton("添加规则");
        addButton.addActionListener(new AddRuleActionListener());
        inputPanel.add(addButton, gbc);

        // 将输入面板添加到主面板的北部
        add(inputPanel, BorderLayout.NORTH);

        // 创建规则列表面板
        JPanel ruleListPanel = new JPanel(new BorderLayout());
        ruleListPanel.setBorder(BorderFactory.createTitledBorder("规则列表"));

        // 创建逻辑关系选择面板
        JPanel logicPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        logicPanel.setBorder(null);
        JLabel logicLabel = new JLabel("逻辑关系：");
        logicComboBox = new JComboBox<>(new String[]{"And", "Or"});
        logicPanel.add(logicLabel);
        logicPanel.add(logicComboBox);

        // 将逻辑关系面板添加到规则列表面板的北部
        ruleListPanel.add(logicPanel, BorderLayout.NORTH);

        // 创建表格
        String[] columnNames = {"规则类型", "规则内容"};
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        ruleTable = new JTable(tableModel);

        // 设置规则类型列居中显示
        DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
        centerRenderer.setHorizontalAlignment(JLabel.CENTER);
        ruleTable.getColumnModel().getColumn(0).setCellRenderer(centerRenderer);

        JScrollPane scrollPane = new JScrollPane(ruleTable);
        // 将表格添加到规则列表面板的中部
        ruleListPanel.add(scrollPane, BorderLayout.CENTER);

        // 将规则列表面板添加到主面板的中部
        add(ruleListPanel, BorderLayout.CENTER);

        // 创建按钮面板
        JPanel buttonPanel = createButtonPanel();
        add(buttonPanel, BorderLayout.SOUTH);
    }


    private JPanel createButtonPanel() {
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));

        JButton removeButton = new JButton("移除规则");
        removeButton.addActionListener(e -> removeSelectedRule());

        JButton modifyButton = new JButton("修改规则");
        modifyButton.addActionListener(e -> modifySelectedRule());

        JButton clearButton = new JButton("清空规则");
        clearButton.addActionListener(e -> clearAllRules());

        buttonPanel.add(removeButton);
        buttonPanel.add(modifyButton);
        buttonPanel.add(clearButton);

        return buttonPanel;
    }

    private class AddRuleActionListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            String ruleType = (String) ruleTypeComboBox.getSelectedItem();
            String ruleContent = ruleContentArea.getText().trim();

            if (ruleType != null && !ruleContent.isEmpty()) {
                Rule rule = new Rule(ruleType, ruleContent);
                rules.add(rule);

                Object[] rowData = {rule.getType(), rule.getContent()};
                tableModel.addRow(rowData);

                ruleContentArea.setText("");
            }
        }
    }

    private void removeSelectedRule() {
        int selectedRow = ruleTable.getSelectedRow();
        if (selectedRow >= 0) {
            rules.remove(selectedRow);
            tableModel.removeRow(selectedRow);
        }
    }

    private void modifySelectedRule() {
        int selectedRow = ruleTable.getSelectedRow();
        if (selectedRow >= 0) {
            Rule rule = rules.get(selectedRow);
            ruleTypeComboBox.setSelectedItem(rule.getType());
            ruleContentArea.setText(rule.getContent());

            rules.remove(selectedRow);
            tableModel.removeRow(selectedRow);
        }
    }

    private void clearAllRules() {
        rules.clear();
        tableModel.setRowCount(0);
        ruleContentArea.setText("");
    }

    /**
     * 获取当前规则列表
     * 供外部调用以获取规则配置
     *
     * @return 规则列表的副本
     */
    public List<Rule> getRules() {
        return new ArrayList<>(rules);
    }

    /**
     * 获取逻辑关系
     *
     * @return 逻辑关系 ("And" 或 "Or")
     */
    public String getLogicRelation() {
        return (String) logicComboBox.getSelectedItem();
    }

    /**
     * 设置逻辑关系
     *
     * @param logicRelation 逻辑关系 ("And" 或 "Or")
     */
    public void setLogicRelation(String logicRelation) {
        logicComboBox.setSelectedItem(logicRelation);
    }

    /**
     * 从字符串加载规则
     *
     * @param rulesContent 规则内容字符串
     */
    public void loadRules(String rulesContent) {
        // 清空现有规则
        clearAllRules();

        // 解析规则内容
        String[] lines = rulesContent.split("\n");
        for (String line : lines) {
            if (!line.trim().isEmpty()) {
                String[] parts = line.split("\\|", 2);
                if (parts.length == 2) {
                    Rule rule = new Rule(parts[0], parts[1]);
                    rules.add(rule);
                    Object[] rowData = {rule.getType(), rule.getContent()};
                    tableModel.addRow(rowData);
                }
            }
        }
    }

    // 规则类
    @SuppressWarnings("ClassCanBeRecord")
    public static class Rule {
        private final String type;
        private final String content;

        public Rule(String type, String content) {
            this.type = type;
            this.content = content;
        }

        public String getType() {
            return type;
        }

        public String getContent() {
            return content;
        }
    }
}
